#!/usr/bin/env python
# -*- coding: utf-8 -*-

import  re
from django.template.loader import render_to_string
import dexml
import exceptions
from dexml import fields
from diff_match_patch import diff_match_patch


class LineContainer(dexml.Model):
	number = fields.String()
	content = fields.String(tagname="initial")
	traduction = fields.String(tagname="traduction")
	start = fields.String(tagname="start")
	end = fields.String(tagname="end")

class DocumentContainer(dexml.Model):
	"""Document lines and title container"""
	title = fields.String()
	lang = fields.String()
	target_lang = fields.String()
	lines = fields.List(LineContainer)



DocumentContainer.meta.tagname = "document"
LineContainer.meta.tagname = "line"

class DocumentLine:
	"""One line for a document"""
	def __init__(self, number, lang, content, start, end):
		self.lang=lang
		self.number=number
		self.content = content
		self.start = start
		self.end = end
		self.traductions = [Traduction()]


class Traduction:
	"""One traduction of a line"""
	def __init__(self):
		self.lang="FR"
		self.content=""

class Difference:
	def __init__(self):
		self.initial=""
		self.first_translation=""
		self.second_translation=""
		self.text_difference=""
		self.html_difference=""

	def __init__(self, first_line, second_line):
	        dmp = diff_match_patch()
		self.initial = first_line.content
		self.first_translation = first_line.traduction
		self.second_translation = second_line.traduction
		self.text_difference = dmp.diff_main(self.second_translation, self.first_translation)
		self.html_difference = dmp.diff_prettyHtml(self.text_difference)


class DocumentFormatter:
	"""Format a document before saving it"""
	def format(self, document):
		"""Modifiy the content attribute of a document"""
		document.content = document.content[3:]
		original_lines = document.content.split("\n")
		lines = []
		number = 0
		i = 0
		while i < len(original_lines):
			#line = original_lines[i].replace(r'\xef\xbb\xbf', '')
			line = original_lines[i].strip()
			if i < 10:
				print("Ligne originale " + str(i) + " : <" + repr(original_lines[i]) + "> ")
				print("Ligne modifiée par strip " + str(i) + " : <" + repr(line) + ">")
			try:
				int(line)
			except exceptions.ValueError:
				i+=1
				continue
			#if not re.match("[0-9]+",line):
				#i+=1
				#continue
			number = line
			i+=1
			line = original_lines[i].strip()
			#print("Ligne " + str(i) + "plitter : <" + line + ">")
			times = line.split("-->")
			start=times[0].strip()
			end=times[1].strip()
			i+=1
			line = original_lines[i].strip()
			content=line
			while line != "":
				i+=1
				line = original_lines[i].strip()
				content += "\n"
				content += line
			lang="EN"
			docLine = DocumentLine(number, lang, content, start, end)
			lines.append(docLine)
		document.content = render_to_string("subfactory/format/subfactory.xml", {'lines': lines, 'document': document})

